const http = require('http');
const path = require('path');
const fs = require('fs');
const server = http.createServer();

server.listen(3000, () => console.log('图书管理接口服务开启'));

server.on('request', (req, res) => {
    // 获取url和method
    let url = req.url;
    let method = req.method; //获取大写的 POST 或 GET
    let books = require(path.join(__dirname, 'books.json'));
    // 判断
    if (method === 'GET' && url === '/api/getbooks') {
        // 满足这个条件，得到所有书籍
        res.setHeader('Content-Type', 'application/json;charset=utf-8');
        let result = {
            status: 200,
            message: '获取成功',
            data: books
        }
        res.end(JSON.stringify(result));
    } else if (method === 'GET' && url.startsWith('/api/delbook')) {
        // 满足这个条件，删除一个书籍
        // 获取id
        let id = req.url.replace(/\D/g, '');
        let result = books.filter(item => { return item.id != id });
        console.log(result);
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        // 把过滤后的结果，存放到books.json中即可
        fs.writeFile(path.join(__dirname, 'books.json'), JSON.stringify(result), err => {
            if (err) {
                console.log(err);
                res.end(JSON.stringify({ status: 400, msg: '删除失败' }));
            } else {
                res.end(JSON.stringify({ status: 200, msg: '删除成功' }));
            }
        });

    } else if (method === 'POST' && url === '/api/addbook') {
        // 满足这个条件，添加一个书籍
    } else {
        res.writeHead(404, {
            'Content-type': 'text/html;charset=utf-8',
        })
        res.end('你请求错了地址！')
    }
})